package com.thread.syn3;

/**
 *一个场景，共同的资源
 * 生产者消费者模式
 *
 * wait（） 等待，释放锁
 *sleep（） 不释放锁
 *notify() 唤醒
 * @author jiangbang
 * @date 2016/7/21
 */
public class synDemo04 {
    public static void main(String[] args) {
        //共同资源
        Movie movie = new Movie();
        //多线程
        Player player = new Player(movie);
        Watcher watcher = new Watcher(movie);

        Thread thread1 = new Thread(player);
        Thread thread2 = new Thread(watcher);
        thread1.start();
        thread2.start();
    }
}


/**
 * 一个场景
 */
class Movie{
    private String pic;
    //flag -- T生产生产,消费者等待，生产完成后通知消费
    //flag -- f消费消费,生产者等待，消费完成后通知生产
    private boolean flag = true;
    //播放
    public synchronized void play(String pic){
        if(!flag){//生产者等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //开始生产
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //生产完毕
        this.pic = pic;
//        System.out.println("生产啦："+pic);
        //通知消费
        this.notify();
        //生产者停下
        this.flag = false;
    }
    //看
    public synchronized void watch(){
        if(flag){//消费者等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //开始消费
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //消费完毕
        System.out.println("消费啦："+pic);
        //通知生产
        this.notifyAll();
        //消费者停下
        this.flag = true;

    }
}

/**
 * 消费者(观看者)
 */
class Watcher implements Runnable{

    private Movie m ;

    public Watcher(Movie m){
        super();
        this.m=m;
    }

    @Override
    public void run() {
        for(int i=0;i<20;i++){
            m.watch();
        }
    }
}


/**
 * 生产者（播放者）
 */
class Player implements Runnable{

    private Movie m ;
    public Player(Movie m){
        super();
        this.m=m;
    }
    @Override
    public void run() {
        for(int i=0;i<20;i++){
            if(0==i%2){
                m.play("左青龙");
            }else{
                m.play("右白虎");
            }
        }
    }
}